<template>
  <div class="product-manage">
    <!-- 头部查询 start -->
    <el-form ref="queryForm" class="query-form" :model="queryParams" size="small" :inline="true">
      <el-form-item label="项目" prop="bind_app_id">
        <el-select v-model="queryParams.bind_app_id" filterable clearable @clear="queryParams.bind_app_id=null">
          <el-option v-for="item in permission_projectList" :value="item.app_id" :label="item.name" :key="item.app_id"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="渠道" prop="channel_id">
        <el-select v-model="queryParams.channel_id" placeholder="请选择" filterable clearable @clear="queryParams.channel_id=null">
          <el-option v-for="item in channelOptions" :key="item.channel_id" :label="`${item.name}(${item.channel_id})`" :value="item.channel_id" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="全部" size="small">
          <el-option :key="10" label="全部" :value="10" />
          <el-option :key="1" label="已上架" :value="1" />
          <el-option :key="0" label="待上架" :value="0" />
        </el-select>
      </el-form-item>
      <el-form-item label="原价区间">
        <el-input-number v-model="numberRange.origin_price_begin"
          :precision="2" placeholder="最低价" :min="0" clearable size="small" style="width: 83px"/>
        -
        <el-input-number v-model="numberRange.origin_price_end"
          :precision="2" placeholder="最高价" :min="0" clearable size="small" style="width: 83px"/>
      </el-form-item>
      <el-form-item label="现价区间">
        <el-input-number v-model="numberRange.price_begin"
          :precision="2" placeholder="最低价" :min="0" clearable size="small" style="width: 83px" />
        -
        <el-input-number v-model="numberRange.price_end"
          :precision="2" placeholder="最高价" :min="0" clearable size="small" style="width: 83px"/>
      </el-form-item>
      <el-form-item label="折扣区间">
        <el-input-number v-model="numberRange.discount_price_begin"
          :precision="2" placeholder="最低价" :min="0" clearable size="small" style="width: 83px" />
        -
        <el-input-number v-model="numberRange.discount_price_end"
          :precision="2" placeholder="最高价" :min="0" clearable size="small" style="width: 83px"/>
      </el-form-item>
      <el-form-item class="big-query" label="折扣生效时间" prop="discountDateRange">
        <el-date-picker v-model="queryParams.discountDateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          range-separator="~"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item class="big-query" label="关键词" prop="keyword">
        <el-input v-model="queryParams.keyword" placeholder="会员套餐名称" clearable size="small" style="width: 210px" @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" size="small" @click="handleQuery">搜索</el-button>
        <el-button size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>
    <!-- 头部查询 end -->
    <el-button type="primary" style="margin-bottom:10px" icon="el-icon-plus" size="small" @click="handleAdd">新增</el-button>
    <div class="text-right">
      <el-popover
        placement="bottom-end"
        popper-class="table-check_popover"
        width="560"
        trigger="click">
        <div>
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">字段选择</el-checkbox>
          <hr/>
          <el-checkbox-group v-model="checkList" @change="handleCheckedChange">
            <div>
              <span class="table-check_label">套餐信息：</span>
              <el-checkbox label="min_version">最低版本</el-checkbox>
              <el-checkbox label="bind_app_id">项目范围</el-checkbox>
              <el-checkbox label="channel_id">渠道范围</el-checkbox>
              <el-checkbox label="product_attrs">所属权益包</el-checkbox>
            </div>
            <div class="mt10" style="padding-left: 70px;">
              <el-checkbox label="name">套餐名称</el-checkbox>
              <el-checkbox label="duration">套餐期限</el-checkbox>
              <el-checkbox label="weight">套餐权重</el-checkbox>
              <el-checkbox label="origin_price">原价</el-checkbox>
            </div>
            <div class="mt10" style="padding-left: 70px;">
              <el-checkbox label="price">现价</el-checkbox>
              <el-checkbox label="apple_price">苹果支付价</el-checkbox>
              <el-checkbox label="cycle_pay_period_price">周期付款价</el-checkbox>
              <el-checkbox label="discount_price">折扣价</el-checkbox>
            </div>
            <div class="mt10" style="padding-left: 70px;">
              <el-checkbox label="show_list">套餐是否展示</el-checkbox>
              <template v-if="isAdditionProduct">
                <el-checkbox label="describe">套餐描述</el-checkbox>
              </template>
              <template v-if="isVipProduct">
                <el-checkbox label="ext.gifts">赠送内容</el-checkbox>
                <el-checkbox label="ext.gifts_desc">赠送描述</el-checkbox>
                <el-checkbox label="ext.gifts_duration">赠送使用期限</el-checkbox>
              </template>
            </div>
            <div class="mt10">
              <span class="table-check_label">套餐交易：</span>
              <el-checkbox label="charge_members">购买人数</el-checkbox>
              <el-checkbox label="charge_times">购买次数</el-checkbox>
            </div>
          </el-checkbox-group>
        </div>
        <el-button type="text" slot="reference">字段选择<i class="el-icon-arrow-down"></i></el-button>
      </el-popover>
    </div>
    <!-- 表格数据 start -->
    <el-table v-loading="loading" :data="dataList" @sort-change="onSortChange">
      <el-table-column label="ID" prop="id"></el-table-column>
      <el-table-column label="最低版本"
        width="120"
        v-if="checkList.includes('min_version')">
        <template slot-scope="scope">
          <span>{{ scope.row.min_version || '--' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="项目范围"
        width="120"
        v-if="checkList.includes('bind_app_id')">
        <template slot-scope="scope">
          <span>{{ scope.row.bind_app_id|translateToName(permission_projectList,'app_id','name') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="渠道范围"
        width="120"
        prop="channel_id"
        v-if="checkList.includes('channel_id')">
         <template #default="{ row }">
           <span>{{row.channelStr}}</span>
        </template>
      </el-table-column>
      <el-table-column label="所属权益包" min-width="150" v-if="checkList.includes('product_attrs')">
        <template slot-scope="scope">
          <span>{{ scope.row.product_attrs|productNameFilter }}</span>
        </template>
      </el-table-column>
      <el-table-column label="套餐名称" min-width="100" prop="show_name" v-if="checkList.includes('name')"/>
      <el-table-column label="套餐期限" width="90" v-if="checkList.includes('duration')">
        <template slot-scope="scope">
          {{ memberTimeOptions.get(scope.row.ext.duration) }}
        </template>
      </el-table-column>
      <el-table-column label="套餐权重" width="80" prop="weight" v-if="checkList.includes('weight')"/>
      <el-table-column label="权益包权益ID" min-width="170" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{ getAttrs(scope.row.relation_right, 'right_id').join(',')}}
        </template>
      </el-table-column>
      <template v-if="isAdditionProduct">
        <el-table-column label="套餐描述" min-width="100" prop="describe" v-if="checkList.includes('describe')"/>
      </template>
      <template v-if="isVipProduct">
        <el-table-column label="赠送内容" min-width="100" v-if="checkList.includes('ext.gifts')">
          <template slot-scope="scope">
            <span v-if="scope.row.ext.gifts && scope.row.ext.gifts[0] && scope.row.ext.gifts[0].amount">{{ scope.row.ext.gifts[0].amount }}{{ scope.row.ext.gifts[0].unit_name }}</span>
          </template>
        </el-table-column>
        <el-table-column label="赠送描述" min-width="100" prop="ext.gifts[0].desc" v-if="checkList.includes('ext.gifts_desc')"/>
        <el-table-column label="赠送使用期限" min-width="120" v-if="checkList.includes('ext.gifts_duration')">
          <template slot-scope="scope">
            <span v-if="scope.row.ext.gifts && scope.row.ext.gifts[0]">
              {{ memberTimeOptions.get(scope.row.ext.gifts && scope.row.ext.gifts[0].duration) }}
            </span>
          </template>
        </el-table-column>
      </template>
      <el-table-column label="原价" width="80" prop="origin_price" v-if="checkList.includes('origin_price')">
        <template #default = {row}>
          {{ row.currency_code==='USD' ? '$':'￥' }}{{ row.origin_price | formatMoney}}
        </template>
      </el-table-column>
      <el-table-column label="现价" width="80" prop="price" v-if="checkList.includes('price')">
        <template #default = {row}>
          {{ row.currency_code==='USD' ? '$':'￥' }}{{ row.price | formatMoney}}
        </template>
      </el-table-column>
      <el-table-column label="苹果支付价" width="90" prop="apple_price" v-if="checkList.includes('apple_price')">
        <template #default = {row}>
          {{ row.currency_code==='USD' ? '$':'￥' }}{{ row.apple_price | formatMoney}}
        </template>
      </el-table-column>
      <!-- <el-table-column label="周期付款" width="90" prop="cycle_pay_flag">
        <template #default = {row}>
          {{ row.cycle_pay_flag ? '启用' : '关闭' }}
        </template>
      </el-table-column> -->
      <el-table-column label="周期付款价" width="90" prop="cycle_pay_period_price" v-if="checkList.includes('cycle_pay_period_price')">
        <template #default = {row}>
          <template v-if="row.cycle_pay_flag||row.enable_wechat_cycle_pay">
            {{ row.currency_code==='USD' ? '$':'￥' }}{{ row.cycle_pay_period_price | formatMoney }}
          </template>
          <template v-else>
            --
          </template>
        </template>
      </el-table-column>
      <el-table-column label="折扣价" width="90" v-if="checkList.includes('discount_price')">
        <template #default = {row}>
          {{ row.currency_code==='USD' ? '$':'￥' }}{{ row.discount_price | formatMoney}}
        </template>
      </el-table-column>
      <el-table-column label="折扣生效时间" width="220">
        <template #default = {row}>
          {{ row.discount_begin | parseTime('{y}-{m}-{d}')}} - {{row.discount_end | parseTime('{y}-{m}-{d}')}}
        </template>
      </el-table-column>
      <el-table-column v-if="checkList.includes('show_list')" label="套餐是否展示" width="220">
        <template #default = {row}>
          {{ row.show_list === 1 ?'展示':'隐藏'}}
        </template>
      </el-table-column>
      <el-table-column label="购买人数" min-width="100" prop="charge_members" sortable="custom" v-if="checkList.includes('charge_members')"/>
      <el-table-column label="购买次数" min-width="100" prop="charge_times" sortable="custom" v-if="checkList.includes('charge_times')"/>
      <!-- <el-table-column label="最近充值时间" min-width="150" prop="last_charge_time" :show-overflow-tooltip="true" /> -->
      <el-table-column label="状态">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" disable-transitions>{{ scope.row.status === 1 ? '已上架' : '待上架' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="180" fixed="right" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button size="small" type="text" @click="handleSaleStatus(scope.row, scope.row.status === 1?0:1)" v-permisaction="['product:status:update']">{{ scope.row.status === 1 ? '下架' : '上架' }}</el-button>
          <el-button size="small" type="text" @click="handleUpdate(scope.row)" v-permisaction="['product:list:update']">修改</el-button>
          <el-button size="small" type="text" @click="handleDiscount(scope.row)" v-permisaction="['product:list:discount']">折扣</el-button>
          <el-button size="small" type="text" @click="handleDelete(scope.row)" :disabled="scope.row.status !== 0" v-permisaction="['product:list:delete']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.page_size" @pagination="getList" />
    <!-- 表格数据 end -->

    <!-- 添加或修改对话框 start -->
    <el-dialog :title="title" :visible.sync="open" width="800px" :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px" style="display: grid;grid-template-columns: repeat(2,1fr);">
        <el-form-item label="最低版本" prop="min_version">
          <el-input v-model="form.min_version" style="width:221px" placeholder="请输入最低版本"/>
        </el-form-item>
        <el-form-item label="项目范围" prop="bind_app_id">
          <el-select v-model="form.bind_app_id" filterable clearable>
            <el-option v-for="item in permission_projectList" :value="item.app_id" :label="item.name" :key="item.app_id"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="渠道范围" prop="channel_id">
          <el-select v-model="form.channel_id" placeholder="请选择" filterable clearable multiple collapse-tags>
            <el-option v-for="item in channelOptions" :key="item.channel_id" :label="`${item.name}(${item.channel_id})`" :value="item.channel_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户分群" prop="ugid_list">
          <el-select
            multiple
            filterable
            v-model="form.ugid_list"
            @keydown.native.delete.capture.stop.prevent
            collapse-tags
            no-data-text="无数据,请尝试选择其他项目"
            popper-class="mw500"
            placeholder="请选择用户分群">
            <el-option v-for="item in userGroupList"
              :key="item.id"
              :label="item.id+'  '+item.name"
              :value="item.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="套餐名称" prop="show_name">
          <el-input v-model="form.show_name" style="width:221px" placeholder="请输入套餐名称"/>
        </el-form-item>

        <el-form-item label="权益包" prop="attr_id">
          <el-select v-model="form.attr_id" placeholder="请选择" @change="handleLevelSelChange()" :disabled="isDisable">
            <el-option v-for="item in rightPackageOptions" :key="item.package_id" :label="item.name" :value="item.package_id" />
          </el-select>
        </el-form-item>
        <el-form-item label="期限名称" prop="name">
          <el-input v-model="form.name" style="width:221px" placeholder="请输入期限名称"/>
        </el-form-item>
        <el-form-item label="套餐期限" prop="ext.duration">
          <el-select v-model="form.ext.duration" placeholder="请选择" :disabled="isDisable">
            <el-option v-for="(item, index) in memberTimeOptions" :key="index" :label="item[1]" :value="item[0]" />
          </el-select>
        </el-form-item>
        <div v-if="isAdditionProduct" style="grid-column: 1 / 3;">
          <el-form-item label="套餐描述" prop="describe">
            <el-input v-model="form.describe" @blur="form.describe=$event.target.value.trim()"/>
          </el-form-item>
        </div>
        <el-form-item label="苹果内购商品ID" prop="apple_id">
          <el-input v-model="form.apple_id" style="width:221px" placeholder="请输入苹果内购商品ID"/>
        </el-form-item>
        <el-form-item label="苹果支付价" prop="apple_price">
          <el-input-number v-model="form.apple_price" :precision="2" :min="0.01"></el-input-number>
        </el-form-item>
        <el-form-item label="原价" prop="origin_price">
          <el-input-number v-model="form.origin_price" :precision="2" :min="0.01"></el-input-number>
        </el-form-item>
        <el-form-item label="现价" prop="price">
          <el-input-number v-model="form.price" :precision="2" :min="0.01"></el-input-number>
        </el-form-item>
        <div style="display: flex;">
          <el-form-item label="支付宝周期付款" prop="cycle_pay_flag">
            <el-switch v-model="form.cycle_pay_flag"></el-switch>
          </el-form-item>
          <el-form-item label="微信周期付款" prop="enable_wechat_cycle_pay">
            <el-switch v-model="form.enable_wechat_cycle_pay"></el-switch>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="周期付款价格" prop="cycle_pay_period_price" v-if="form.cycle_pay_flag||form.enable_wechat_cycle_pay">
            <el-input-number v-model="form.cycle_pay_period_price" :precision="2" :min="0.01"></el-input-number>
          </el-form-item>
        </div>
        <el-form-item label="签约类型" prop="cycle_pay_sign_type" v-if="form.cycle_pay_flag||form.enable_wechat_cycle_pay">
          <el-select v-model="form.cycle_pay_sign_type" placeholder="请选择" >
            <el-option label="仅签约" value="only_sign" />
            <el-option label="支付并签约" value="pay_and_sign" />
          </el-select>
        </el-form-item>
        <template v-if="form.cycle_pay_flag||form.enable_wechat_cycle_pay">
          <el-form-item label="周期付款周期" prop="ext.cycle_pay_duration" v-if="form.cycle_pay_sign_type === 'pay_and_sign'">
            <el-select v-model="form.ext.cycle_pay_duration" placeholder="请选择" :disabled="isDisable">
              <el-option v-for="(item, index) in cycleTimeOptions" :key="index" :label="item[1]" :value="item[0]" />
            </el-select>
          </el-form-item>

          <el-form-item label="微信模版ID" prop="wechat_plant_id" v-if="form.enable_wechat_cycle_pay">
            <el-input v-model="form.wechat_plant_id"></el-input>
          </el-form-item>
        </template>

        <div style="grid-column: 1 / 3;">
          <el-form-item label="套餐权重" prop="weight">
            <el-input-number v-model="form.weight" :precision="0" :min="0"></el-input-number>
          </el-form-item>
        </div>
        <div style="grid-column: 1 / 3;">
          <el-form-item label="套餐是否展示" prop="show_list">
            <el-switch
              v-model="form.show_list" :active-value="1" :inactive-value="0">
            </el-switch>
            <el-tooltip class="item" effect="dark" content="开启时该套餐将会在应用内套餐购买页展示，关闭则不显示" placement="top-end">
              <i class="el-icon-question" style="margin-left: 10px;cursor: pointer;"></i>
            </el-tooltip>
          </el-form-item>
        </div>
        <template v-if="isVipProduct">
          <div style="grid-column: 1 / 3;" class="modules-title">
            <span>赠送配置（非必填）</span>
          </div>
          <el-form-item label="权益配置">
            <el-row>
              <el-col :span="18">
                <el-form-item prop="ext.gifts[0].unit_id">
                  <el-select v-model="form.ext.gifts[0].unit_id" style="width: 160px;">
                    <el-option v-for="item in chargeUnitList" :value="item.unit_id" :label="item.internal_name" :key="item.unit_id"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item prop="ext.gifts[0].amount">
                  <el-input-number v-model="form.ext.gifts[0].amount" :min="0" :precision="0" controls-position="right" style="width: 100px;"></el-input-number>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form-item>

          <el-form-item label="使用期限" prop="ext.gifts[0].duration" key="ext.gifts[0].duration">
            <el-select v-model="form.ext.gifts[0].duration" placeholder="请选择" :disabled="!form.ext.gifts[0].amount">
              <el-option v-for="(item, index) in memberTimeOptions" :key="index" :label="item[1]" :value="item[0]"/>
            </el-select>
          </el-form-item>
          <div style="grid-column: 1 / 3;">
            <el-form-item label="赠送描述" prop="ext.gifts[0].desc">
              <el-input v-model="form.ext.gifts[0].desc" @blur="form.ext.gifts[0].desc=$event.target.value.trim()" :disabled="!form.ext.gifts[0].amount"/>
            </el-form-item>
          </div>
        </template>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open = false">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加或修改对话框 end -->
    <el-dialog title="编辑折扣" :visible.sync="discountShow" width="600px" :close-on-click-modal="false">
      <el-form ref="discountForm" :model="discountForm" :rules="rules" label-width="120px">
        <el-form-item label="会员套餐">
          <span>{{discountForm.show_name}}</span>
        </el-form-item>
        <el-form-item label="原价">
          <span> {{ discountForm.origin_price | formatMoney}}</span>
        </el-form-item>
        <el-form-item label="现价">
           {{ discountForm.price | formatMoney}}
        </el-form-item>
        <el-form-item label="折扣价" prop="discount_price">
          <el-input-number v-model="discountForm.discount_price" :precision="2" :min="0.01"></el-input-number>
        </el-form-item>
        <el-form-item label="生效时间" prop="discount_date">
          <el-date-picker v-model="discountForm.discount_date"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          </el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitDiscount">确 定</el-button>
        <el-button @click="discountShow = false">取 消</el-button>
      </div>
    </el-dialog>
    <AuthCode :visible.sync="openAuth" ref="AuthCode" :title="authTitle" :authObj="authObj" @submit="submitAuthCode"/>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import AuthCode from '@/components/auth-code'
import { productList, addMenu, updateMenu, delMenu, updateStatus, sendCode } from '@/api/member/product'
import { getPackageList } from '@/api/addition'
import { listRightPackage } from '@/api/rights/package'
import { listUserGroup } from '@/api/user-clustering'
import { getMemberValidTime, getCycleValidTime } from '@/constants/constant'
import { formatMoney, parseTime } from '@/utils'
import storage from '@/utils/storage'
import { getChannelByAppId } from '@/api/system/channel'
import { getChargeUnit } from '@/api/system'
const tableOpt = ['min_version', 'bind_app_id', 'channel_id', 'product_attrs', 'name', 'duration', 'weight', 'origin_price', 'price', 'apple_price', 'cycle_pay_period_price', 'discount_price', 'charge_members', 'last_charge_time', 'charge_times', 'show_list']
export default {
  name: 'Product',
  components: { AuthCode },
  data () {
    return {
      pageName: '',
      // 遮罩层
      loading: true,
      // 总条数
      total: 0,
      // 会员套餐表格数据
      dataList: null,
      // 弹出层标题
      title: '',
      authTitle: '',
      // 是否显示弹出层
      open: false,
      openAuth: false,
      discountShow: false, // 折扣弹窗
      // 会员等级选项
      memberTimeOptions: undefined,
      // 会员等级选项
      rightPackageOptions: [],
      // 计费单位
      chargeUnitList: [],
      // 选择的会员等级对应的权益
      rights: [],
      channelOptions: [],
      userGroupList: [],
      // 周期付款周期选项
      cycleTimeOptions: undefined,
      // 表单参数
      form: {
        id: null,
        min_version: null,
        bind_app_id: null,
        channel_id: null,
        ugid_list: [],
        ext: {
          duration: null,
          cycle_pay_duration: null,
          gifts: [
            {
              type: 'charge',
              unit_id: null,
              unit_name: null,
              amount: null,
              duration: null,
              desc: null
            }
          ]
        },
        weight: 0,
        show_name: '',
        name: '',
        apple_id: '',
        apple_price: 1,
        attr_id: null,
        origin_price: 1,
        price: 1,
        attr_type: 1,
        unlimited: false,
        cycle_pay_flag: false,
        cycle_pay_period_price: 1,
        enable_wechat_cycle_pay: false,
        cycle_pay_sign_type: 'only_sign',
        wechat_plant_id: '',
        show_list: 1,
        describe: ''
      },
      discountForm: {
        discount_price: 1,
        discount_date: null
      },
      authObj: {},
      // 查询参数
      queryParams: {
        bind_app_id: null,
        channel_id: null,
        page: 1,
        page_size: 10,
        status: 10,
        discountDateRange: null,
        attr_types: [2],
        keyword: undefined
      },
      // 查询数字区间参数
      numberRange: {
        origin_price_begin: undefined,
        origin_price_end: undefined,
        price_begin: undefined,
        price_end: undefined,
        discount_price_begin: undefined,
        discount_price_end: undefined
      },
      isIndeterminate: false,
      checkAll: false,
      checkList: [],
      // 表单校验
      rules: {
        show_name: [
          { required: true, message: '会员套餐名称不能为空', trigger: 'blur' }
        ],
        ugid_list: [
          { max: 10, type: 'array', message: '最多可选10个用户分群', trigger: 'change' }
        ],
        name: [
          { required: true, message: '期限名称不能为空', trigger: 'blur' }
        ],
        attr_id: [
          { required: true, message: '权益包不能为空', trigger: 'blur' }
        ],
        discount_price: [
          { required: true, message: '折扣价不能为空', trigger: 'blur' }
        ],
        discount_date: [
          { required: true, type: 'array', message: '生效日期不能为空', trigger: 'blur' }
        ],
        'ext.duration': [
          { required: true, message: '套餐权重不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters('zcsd-core', ['permission_projectList']),
    isDisable () {
      return this.form.id && this.form.status === 1
    },
    isAdditionProduct () {
      return this.pageName === 'AdditionProduct'
    },
    isVipProduct () {
      return this.pageName === 'Product'
    }
  },
  filters: {
    productNameFilter (val) {
      const arr = []
      for (const item of val) {
        arr.push(item.name)
      }
      return arr.join('，')
    }
  },
  async created () {
    this.pageName = this.$route.name
    if (this.pageName === 'AdditionProduct') {
      this.queryParams.attr_types = [6]
      getPackageList({ page: 1, page_size: 100, status: 'published' }).then(res => {
        this.rightPackageOptions = (res.data.list || []).map(item => {
          item.package_id = item.id
          return item
        })
      })
    } else {
      listRightPackage({ page: 1, page_size: 100, status: 1 }).then(res => {
        this.rightPackageOptions = res.data.list || []
      })

      getChargeUnit().then(res => {
        this.chargeUnitList = (res.data.list || [])
      })
    }
    const list = this.permission_projectList.map(item => item.app_id)
    this.memberTimeOptions = getMemberValidTime()
    this.cycleTimeOptions = getCycleValidTime()
    this.checkList = storage.get('productTable') || [...tableOpt]
    this.handleCheckedChange(this.checkList)
    await getChannelByAppId({ app_ids: list.join(',') }).then(res2 => {
      this.channelOptions = res2.data.list
    })
    this.getList()
    this.getUserGroupList()
  },
  methods: {
    getUserGroupList () {
      listUserGroup({
        page: 1,
        page_size: 100,
        status: 'publish'
        // appid: this.formData.app_id.join(',')
      }).then(res => {
        this.userGroupList = res.data.list || []
      })
    },
    handleCheckAllChange (val) {
      this.checkList = val ? [...tableOpt] : []
      this.isIndeterminate = false
      storage.set('productTable', this.checkList)
    },
    handleCheckedChange (value) {
      let checkedCount = value.length
      const count = tableOpt.length
      this.checkAll = checkedCount === count
      this.isIndeterminate = checkedCount > 0 && checkedCount < count
      storage.set('productTable', value)
    },
    onSortChange ({ prop, order }) {
      this.queryParams.sort_field = order ? prop : null
      this.queryParams.sort_method = order === 'descending' ? 'desc' : 'asc'
      this.getList()
    },
    /** 查询用户列表 */
    getList () {
      this.loading = true
      productList(this.queryParams).then(response => {
        this.dataList = response.data.list.map(item => {
          if (Array.isArray(item.channel_id)) {
            item.channelStr = item.channel_id.map(id => this.$root.$options.filters.translateToName(id, this.channelOptions, 'channel_id', 'name')).join(',')
          }
          if (typeof item.channel_id === 'string') {
            item.channelStr = this.$root.$options.filters.translateToName(item.channel_id, this.channelOptions, 'channel_id', 'name')
          }
          return item
        })
        this.total = response.data.count || 0
      }).finally(() => {
        this.loading = false
      })
    },
    // 表单重置
    reset () {
      this.resetForm('form')
      this.rights = []
      this.form.status = 0
      this.form.id = null
    },
    /** 搜索按钮操作 */
    handleQuery () {
      const { queryParams, numberRange } = this
      const isValid = this.validNumberRangeInput(queryParams, 'origin_price_begin', 'origin_price_end') &&
                      this.validNumberRangeInput(queryParams, 'price_begin', 'price_end') &&
                      this.validNumberRangeInput(queryParams, 'discount_price_begin', 'discount_price_end')
      if (!isValid) {
        this.msgError('请检查价格区间输入')
        return
      }
      queryParams.page = 1
      Object.keys(numberRange).forEach(key => {
        const item = numberRange[key]
        queryParams[key] = item ? item * 100 : undefined
      })
      if (this.queryParams.discountDateRange) {
        queryParams.discount_begin_time = this.queryParams.discountDateRange[0]
        queryParams.discount_end_time = this.queryParams.discountDateRange[1]
      } else {
        queryParams.discount_begin_time = null
        queryParams.discount_end_time = null
      }
      this.queryParams = { ...queryParams }
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery () {
      Object.keys(this.numberRange).forEach(key => {
        this.numberRange[key] = undefined
      })
      this.resetForm('queryForm')
      this.handleQuery()
    },
    /** 权益下拉框操作 */
    handleLevelSelChange () {
      let selLevel = this.rightPackageOptions.filter(item => item.package_id === this.form.attr_id)[0] || {}
      this.form.pkg_name = selLevel.name
    },
    /** 新增按钮操作 */
    handleAdd () {
      this.reset()
      this.open = true
      this.title = '添加会员套餐'
    },
    /** 修改按钮操作 */
    handleUpdate (row) {
      const { origin_price, price } = row
      this.reset()
      this.open = true
      this.title = '修改会员套餐'
      this.$nextTick(() => {
        this.form = {
          id: row.id,
          min_version: row.min_version || null,
          bind_app_id: row.bind_app_id || null,
          channel_id: typeof row.channel_id === 'string' ? [row.channel_id] : row.channel_id,
          ext: {
            duration: row.ext.duration,
            cycle_pay_duration: row.ext.cycle_pay_duration,
            gifts: row.ext.gifts ? JSON.parse(JSON.stringify(row.ext.gifts)) : [
              {
                type: 'charge',
                unit_id: null,
                unit_name: null,
                amount: null,
                duration: null,
                desc: null
              }
            ]
          },
          ugid_list: row.ugid_list || [],
          weight: row.weight,
          name: row.name,
          show_name: row.show_name,
          describe: row.describe,
          apple_id: row.apple_id,
          apple_price: formatMoney(row.apple_price),
          attr_id: row.product_attrs.map(item => item.attr_id)[0],
          origin_price: formatMoney(origin_price),
          price: formatMoney(price),
          attr_type: row.attr_type,
          unlimited: row.unlimited,
          status: row.status,
          cycle_pay_flag: !!row.cycle_pay_flag,
          cycle_pay_period_price: formatMoney(row.cycle_pay_period_price || 0),
          enable_wechat_cycle_pay: !!row.enable_wechat_cycle_pay,
          cycle_pay_sign_type: row.cycle_pay_sign_type || 'only_sign',
          wechat_plant_id: row.wechat_plant_id,
          show_list: row.show_list
        }
        this.handleLevelSelChange()
      })
    },
    handleDiscount (row) {
      this.resetForm('discountForm')
      this.$nextTick(() => {
        this.discountForm.id = row.id
        this.discountForm.show_name = row.show_name
        this.discountForm.origin_price = row.origin_price
        this.discountForm.price = row.price
        this.discountForm.discount_price = formatMoney(row.discount_price)
        if (row.discount_begin) {
          this.discountForm.discount_date = [parseTime(row.discount_begin, '{y}-{m}-{d}'), parseTime(row.discount_end, '{y}-{m}-{d}')]
        } else {
          this.discountForm.discount_date = null
        }
        this.discountShow = true
      })
    },
    /** 上/下架按钮 */
    handleSaleStatus (row, status) {
      this.authTitle = `确认要${status === 1 ? '上' : '下'}架该商品吗？验证码通过验证后才可进行操作`
      this.authObj = {
        status,
        type: status === 1 ? 'product_shelf' : 'product_removed',
        data: {
          product_id: row.id
        }
      }
      this.openAuth = true
    },
    /** 提交按钮 */
    submitForm () {
      const { form } = this
      const { origin_price, price } = this.form
      // eslint-disable-next-line sonarjs/cognitive-complexity
      this.$refs['form'].validate(valid => {
        if (valid) {
          if (this.form.enable_wechat_cycle_pay && !this.form.wechat_plant_id) {
            this.$message.error('请填写微信模板ID或关闭微信周期付款！')
            return
          }
          if (form.ext.gifts[0].amount) {
            if (!form.ext.gifts[0].unit_id) {
              this.$message.error('赠送配置中的计费单位不能为空！')
              return
            }
            if (!form.ext.gifts[0].duration) {
              this.$message.error('赠送配置中的使用期限不能为空！')
              return
            }
            if (!form.ext.gifts[0].desc) {
              this.$message.error('赠送配置中的赠送描述不能为空！')
              return
            }
            form.ext.gifts[0].unit_name = this.$options.filters.translateToName(form.ext.gifts[0].unit_id, this.chargeUnitList, 'unit_id', 'name')
          }
          const params = {
            attr_id: [form.attr_id],
            origin_price: Math.round(origin_price * 100),
            price: Math.round(price * 100),
            attr_type: this.pageName === 'AdditionProduct' ? 6 : 2,
            id: form.id,
            weight: form.weight,
            ext: Object.assign({}, form.ext),
            name: form.name,
            apple_id: form.apple_id,
            ugid_list: form.ugid_list,
            apple_price: Math.round(form.apple_price * 100),
            status: 0,
            show_name: form.show_name,
            unlimited: form.ext.duration === 36792000,
            bind_app_id: parseInt(form.bind_app_id) || 0,
            channel_id: form.channel_id || [],
            min_version: form.min_version || '',
            cycle_pay_flag: form.cycle_pay_flag,
            cycle_pay_period_price: form.cycle_pay_period_price ? Math.round(form.cycle_pay_period_price * 100) : 0,
            enable_wechat_cycle_pay: form.enable_wechat_cycle_pay,
            cycle_pay_sign_type: form.cycle_pay_sign_type,
            wechat_plant_id: form.wechat_plant_id,
            show_list: form.show_list
          }

          if (!params.ext.gifts[0].amount) {
            delete params.ext.gifts
          }

          if (this.isAdditionProduct) {
            params['describe'] = form.describe
          }
          if (form.ext.gifts[0].amount) {
            params.ext.gifts = form.ext.gifts
          }
          if (!(form.cycle_pay_flag || form.enable_wechat_cycle_pay) || form.cycle_pay_sign_type !== 'pay_and_sign') {
            delete params.ext.cycle_pay_duration
          }
          if (this.form.id) {
            updateMenu(params).then(response => {
              this.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addMenu(params).then(response => {
              this.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    submitDiscount () {
      this.$refs['discountForm'].validate(valid => {
        if (valid) {
          const params = {
            discount_begin: this.discountForm.discount_date[0] + ' 00:00:00',
            discount_end: this.discountForm.discount_date[1] + ' 23:59:59',
            discount_price: Math.round(this.discountForm.discount_price * 100),
            id: this.discountForm.id
          }
          updateMenu(params).then(response => {
            this.msgSuccess('编辑成功')
            this.discountShow = false
            this.getList()
          })
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete (row) {
      this.authObj = {
        type: 'product_deleted',
        data: {
          product_id: row.id
        }
      }
      sendCode(Object.assign({ mock: true }, this.authObj)).then(res => {
        if (res.data.need_verify) {
          this.authTitle = `确认要删除该商品吗？验证码通过验证后才可进行操作`
          this.openAuth = true
        } else {
          this.$confirm('是否确认删除"' + row.show_name + '"?', '警告', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.deleteProduct({
              code: res.data.code,
              vid: res.data.vid
            })
          })
        }
      })
    },

    submitUpdateStatus (codeObj) {
      updateStatus({ id: this.authObj.data.product_id, status: this.authObj.status }, codeObj).then(() => {
        this.openAuth = false
        this.getList()
        this.msgSuccess('操作成功')
      }).catch(() => {
        this.$refs.AuthCode.cancelLoading()
      })
    },
    deleteProduct (codeObj) {
      delMenu({ id: this.authObj.data.product_id }, codeObj).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
        this.openAuth = false
      }).catch(() => {
        this.$refs.AuthCode.cancelLoading()
      })
    },
    submitAuthCode (codeObj) {
      if (this.authObj.type === 'product_deleted') {
        this.deleteProduct(codeObj)
      } else {
        this.submitUpdateStatus(codeObj)
      }
    }
  }
}
</script>
